{% extends "base.html" %}
{% load static %}
{% load universal %}
{% load gravatar %}
{% load render_kinetics %}



{% block title %}Kinetics Data{% endblock %}
{% block extrahead %}
<script src="https://code.highcharts.com/6/highcharts.js"></script>
<script src="{% static 'js/highcharts.theme.js' %}" type="text/javascript"></script>

<script type="text/javascript">
jQuery(document).ready(function() {

    kineticsModelList = [];

    {% for reactants, arrow, products, entry, kinetics, source, href, forward in kineticsDataList %}
    kseries = [];
    {{ kinetics|get_rate_coefficients:user }}
    {% if kinetics %}
    {% include "kineticsModel.js" %}
    kineticsModelList.push(kseries[kseries.length-1]);
    {% endif %}
    {% endfor %}

    MathJax.Hub.Queue(function() {
        // Do these things once MathJax has finished rendering.
        kchart = plotKinetics('plotk', kineticsModelList);
        if (kineticsModelList.length > 1) {
            calculateAverage();
        }
    });

    /* For the kinetics search form */

    /* sort CAS numbers numerically by what's up to the first hyphen */
    /* The NIST kinetics site seems to usually choose the lowest assigned CAS number */
    function sortCAS(a,b){
        return a.split('-')[0] - b.split('-')[0];
    }

    function resolve(fieldName){
        var field = $('input[name="'+fieldName+'"]')
        var value = field.val();
        if (value != "") {
            /* try resolving by CAS number */
            //var url = '/cactus/'+escape(value)+'/cas';
            var url = '/nistcas/'+escape(value);
            var jqxhr =  $.get(url,function(resolved_name) {
                field.val(resolved_name.split('\n').sort(sortCAS)[0]);
            }).on('error', function() { /* no CAS number assigned (or some other problem) so use chemical formula */
                var formula = value.split('/')[1]; /* formula is first layer of InChI */
                field.val(formula);
            })
        }
   }
   resolve("text1");
   resolve("text2");
   resolve("text3");
   resolve("text4");
   /* End of code for the kinetics search form */

});


var average_stale = true;
{% include "kineticsPlot.js" %}

function getVisible(chart) {
    // Returns an array of true/false values corresponding to vilibility of each series in the chart.
    var visible = [chart.series.length];
    for (var i = 0; i < chart.series.length; i++)
        visible[i] = chart.series[i].visible;
    return visible;
};

function calculateAverage() {
    // Calculates the average of the visible rates on the chart. 
    visible = getVisible(kchart);
    AAverage = 0.0;
    nAverage = 0.0;
    EaAverage = 0.0;
    count = 0;
    var highChartsSeriesIndex = 0
    refList = '';
    {% for reactants, arrow, products, entry, kinetics, source, href, forward in kineticsDataList %}
    {% if kinetics %}
    if (visible[highChartsSeriesIndex]) {
        {{ kinetics|get_rate_coefficients:"A_n_Ea" }} {# returns A=, n=, Ea=, Aunits=, Eunits=, and Pnote= #}
        AAverage += Math.log(A);
        nAverage += n;
        EaAverage += Ea;
        count += 1;
        {% if entry.reference %}refList += count + '. {{ entry.reference.authors.0 }}, {{ entry.reference.year }}{% if entry.reference.url %} {{ entry.reference.url }}{% endif %}'+Pnote+'\n';
        {% else %}refList += count + '. {{ source }}'+Pnote+'\n';{% endif %}
        {{ kinetics|get_user_kfactor:user }}
    }
    highChartsSeriesIndex++;
    {% else %} // {{ source }} had no kinetics. Not included in plot, so can't average.
    {% endif %}{% endfor %}

    AAverage = Math.exp(AAverage / count);
    nAverage /= count;
    EaAverage /= count;
    
    {% if new_entry_form %}
    if (count == 0) document.getElementById("train").disabled = true
    else document.getElementById("train").disabled = false;

    output = document.getElementById("id_entry").value.split('kinetics')[0] +
            'kinetics = Arrhenius(\n        A = (' + AAverage.toExponential(5) + ',\"' + Aunits + '\"),' +
            '\n        n = (' + nAverage.toFixed(5) + ',\"\"),' +
            '\n        Ea = (' + EaAverage.toExponential(5) + ',\"' + Eunits + '\"),' +
            '\n        T0 = (1,\"K\"),' +
            '\n    ),' +
            '\n    reference = None,' +
            '\n    reference_type = \"\",' +
            '\n    short_desc = u\"\"\"User-generated average\"\"\",' +
            '\n    long_desc = ' +
            '\nu\"\"\"' +
            '\nAverage of ' + count + ' results:' +
            '\n' + refList + '\"\"\",';
    document.getElementById("id_entry").value = output;
    {% endif %}
    
    var new_data = [];
    for (var n = 0; n <= 10; n++){
        T = 1/( 1/300 + (1/2000-1/300)*n/10 );
        k = kfactor * AAverage * Math.pow(T,nAverage) * Math.exp(-1*EaAverage / (8.314472 * T));
        new_data.push([1000.0/T, Math.log(k)/Math.LN10 ]);
    }
    average_stale = false;
    kchart.get('average').setData(new_data, false); // don't redraw automatically, because this function is called on redraw!
    setTimeout(function(){ kchart.redraw(); },50); // redraw after delay
};

function insertSquib() {
    input = document.getElementById("id_entry").value.split('    kinetics')[0];
    squib = document.getElementById("id_new_squib").value;
    output = '    label = "' + squib + '",\n' + input +
             '    kinetics = None,\n' +
             '    reference = None,\n' +
             '    reference_type = \"\",\n' +
             '    short_desc = u\"\"\"\"\"\",\n' +
             '    long_desc = \n' +
             'u\"\"\"\n\n\"\"\",';
    document.getElementById("id_new_squib_entry").value = output;
}
</script>

<style>
   .NIST_query {
    background: #eee;
    background-image: url('http://webbook.nist.gov/chemistry/img/nist-link-left.gif');
    background-repeat: no-repeat;
    background-position: 2px center;
    border: 1px solid #993333;
    padding: 6px;
    padding-left: 138px;
    margin: 5px;
    min-height: 30px;
    text-align: right;
   }
   .NIST_query input[type=text] {
      width: 18%;
      font-size: 75%;
      background: transparent;
   }

</style>
{% endblock %}

{% block navbar_items %}
<li><a href="{% url 'database:index' %}">Database</a></li>
<li><a href="{% url 'database:kinetics' %}">Kinetics</a></li>
<li><a href="{% url 'database:kinetics-search' %}">Search</a></li>
{% endblock %}

{% block sidebar_items %}
{% endblock %}

{% block page_title %}Kinetics Data{% endblock %}

{% block page_body %}

{% if reactionUrl != '' %}
<p><a href="{{ reverseReactionURL }}">Search reverse reaction kinetics.</a></p>
{% endif %}

<div class="NIST_query">
         <form name="UserForm" action="http://kinetics.nist.gov/kinetics/Search.jsp" method="POST" target="_blank">
            <input type=hidden name="doc" VALUE="SearchForm">
            <input type=hidden name="type" VALUE="java">
            <input type=hidden name="Units" VALUE="">
            <input type=hidden name="database" VALUE="kinetics">
            <input type=hidden name="numberOfFields" VALUE="5">
            <input type=hidden name="boolean1" value="">
            <input type=hidden name="lp1" value=" ">
            <input type=hidden name="field1" value="reactants">
            <input type=hidden name="relate1" value="=">
            <input type=text   name="text1" value="{{ reactantInChIs.0 }}">
            <input type=hidden name="rp1" value=" ">
            <input type=hidden name="boolean2" value="and">
            <input type=hidden name="lp2" value=" ">
            <input type=hidden name="field2" value="reactants">
            <input type=hidden name="relate2" value="=">+
            <input type=text   name="text2" value="{{ reactantInChIs.1 }}">
            <input type=hidden name="rp2" value=" ">
            <input type=hidden name="boolean3" value="and">
            <input type=hidden name="lp3" value=" ">
            <input type=hidden name="field3" value="products">
            <input type=hidden name="relate3" value="=">=
            <input type=text   name="text3" value="{{ productInChIs.0 }}">
            <input type=hidden name="rp3" value=" ">
            <input type=hidden name="boolean4" value="and">
            <input type=hidden name="lp4" value=" ">
            <input type=hidden name="field4" value="products">
            <input type=hidden name="relate4" value="=">+
            <input type=text   name="text4" value="{{ productInChIs.1 }}">
            <input type=hidden name="rp4" value=" ">
            <input type=hidden name="boolean5" value="and">
            <input type=hidden name="lp5" value=" ">
            <input type=hidden name="field5" value="kinetics.squib">
            <input type=hidden name="relate5" VALUE="~*">
            <input type=hidden name="text5" value="">
            <input type=hidden name="rp1" value=" "> <br />
            <input type=submit value="Search NIST kinetics" id="submit">
            <input type=hidden name="category" value="0">
            <a href="http://kinetics.nist.gov/kinetics/index.jsp?v=cm&m=Mole&e=kJ&t=K&p=Pa&rt=1.0" title="Set units at NIST" target="_blank">set units</a>
         </form>
</div>
{% if new_entry_form %}
<div align="right">
    <form name="SquibForm" onSubmit="insertSquib()" action="{% url 'database:kinetics-entry-new' family=subsection type="NIST" %}" method="POST">
        {% csrf_token %}
        Have NIST data for this reaction? Enter the squib here to import it:
        <input type=text value="" id="id_new_squib">
        <div style="display: none;"><textarea name="entry" id="id_new_squib_entry"></textarea></div>
        <div style="display: none;"><input type=text name="change" value="none"></div>
        <input type=submit value="Go">
    </form>
</div>
{% endif %}
{% if kineticsDataList|length > 0 %}

{% for reactants, arrow, products, entry, kinetics, source, href, forward in kineticsDataList %}
<h3>
{% if href != '' %}<a href="{{ href }}">{% endif %}
Result #{{ forloop.counter }} - {{ source }}{% if entry.index != -1 %}/{{entry.index }}{% endif %}
{% if href != '' %}</a>{% endif %}
{% if entry.reference %} - {% if entry.reference.url %}<a href="{{ entry.reference.url }}">{% endif %}<span title="{{ entry.reference|get_ref_tooltip }}">{% filter split:','|first %}{{ entry.reference.authors.0 }}{% endfilter %}, {{ entry.reference.year }}</span>{% if entry.reference.url %}</a>{% endif %}{% endif %}
{% if not forward %} *{% endif %}
</h3>

<p><span class="reactants">{{ reactants|safe }}</span>{{ arrow|safe }}<span class="products">{{ products|safe }}</span></p>

{{ kinetics|render_kinetics_math:user }}

{% if source == 'RMG-Java' %}
<P>Comments: {{ entry.long_desc }}
{% endif %}

{% if not forward %}<p>* Kinetics fitted from reverse direction</p>{% else %}<br/>{% endif %}
{% endfor %}

<div id="plotk" style="width: {{ plotWidth }}px; height: {{ plotHeight }}px; margin: auto;"></div>

{% if new_entry_form %}
<form method="post" id="entry_form" onSubmit="calculateAverage()" action="{% url 'database:kinetics-entry-new' family=subsection type="training" %}">
<div style="display: none;">{{ new_entry_form.entry }}</div>
{% csrf_token %}
<div align="center">
<input id="train" type="submit" value="Create training rate from average" />
</div>
</form>
{% endif %}

{% else %}
<p>No results found.</p>
{% endif %}

<P><br>

<div align="center">
<table>
<tr><th colspan="2"><hr>  <h3><b>Evaluate Rates</b></h3></th></tr>
    <form action="" method="POST">{% csrf_token %}
<tr><td colspan="2" align="center">Temperature: {{ form.temperature }} {{ form.temperature_units }} 
    		Pressure: {{ form.pressure }} {{form.pressure_units}}  <input type="submit" value="Submit" name="submit"></td></tr>
    </form>
{% if eval %}
{% for reactants, arrow, products, entry, kinetics, source, href, forward in kineticsDataList %}
<tr><td>{{ forloop.counter }}. {{ source }}</td><td>{{ kinetics|get_specific_rate:eval }}</td>
</tr>
{% endfor %}
{% endif %}

</table>
</div>

{% endblock %}
